#!/usr/bin/env python
#coding:utf-8
#天气预报程序：今天，明天，后天三天的天气情况

import urllib2,re
import sys
import pygtk
import gtk
import gtk.glade

pygtk.require("2.0")

def getPage(url):
    '''读取网页内容
    '''
    page = urllib2.urlopen(url)
    page_content = page.read()
    page.close()
    return page_content

def getWeather(webPage):
    '''获取字段中所需要的信息，当记录下来
    '''
    weather=''
    regex=r'<div class="Weather_TP">(.*)</div>'    # 太强大了，(.*)这里面的东西，正是我们所需要的天气情况
    #match=re.findall(regex,webPage)    # 利用findall()找出信息，并放到match列表中
    match=re.findall(regex, webPage.decode('gbk').encode('utf-8'))
    #type(match)
    #weather = match[0].decode('gbk').encode('utf-8')  # Wyatt.Wang，这儿的 match 是个列表，所以要用 match[0]
    weather = '今天： %s\n明天： %s\n后天： %s' % (match[0], match[1], match[2])
    return weather

def showWeather(url):
    '''打印出检索到的信息
    '''
    page_content=getPage(url)
    weather=getWeather(page_content)
    #type(weather)
    return weather
   
class weatherGTK():

    def __init__(self):
        self.gladefile = 'iw3.glade'
        self.wTree = gtk.glade.XML(self.gladefile)
        self.window = self.wTree.get_widget("window1")
        self.window.show()

        dic = {"on_window1_destory":gtk.main_quit,
               "on_buttonOK_clicked":self.buttonOK}
        self.wTree.signal_autoconnect(dic)
        self.window.connect('destroy', gtk.main_quit) #退出窗口
        
    def buttonOK(self, widget):

        print widget.get_name()
        self.city = self.wTree.get_widget('text_in').get_text()
        print self.city
        self.url = 'http://php.weather.sina.com.cn/search.php?f=1&city=%s&dpc=1'%self.city.decode('utf8').encode('gbk')
        self.s = showWeather(self.url)
        #type(self.s)
        self.wTree.get_widget('text_out').get_buffer().set_text(self.s)
       
       
    def main(self):
        gtk.main()
 
if __name__ == '__main__':
    iw = weatherGTK()
    iw.main()
